{
 "cells": [
  {
   "cell_type": "code",
   "id": "f0051bfe",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-11-19T00:16:34.006718Z",
     "start_time": "2025-11-19T00:16:27.398254Z"
    }
   },
   "source": [
    "# print('llm 调用tools 让llm 和外界交流')\n",
    "# llm 调用tools 让llm 和外界交流\n",
    "# # 发起请求的服务\n",
    "\n",
    "# !pip install requests\n",
    "# !pip install openai\n",
    "import requests\n",
    "# python 类型约定，\n",
    "# js 弱类型语言 \n",
    "# -> str 返回值的类型\n",
    "def get_weather(location: str) -> str:\n",
    "    url = \"https://api.seniverse.com/v3/weather/now.json\"\n",
    "    params = {\n",
    "        \"key\": \"SaVSOt7sYbwpka9iv\",\n",
    "        \"location\": location,\n",
    "        \"language\": \"zh-Hans\"\n",
    "    }\n",
    "    try:\n",
    "        resp = requests.get(url, params=params, timeout=10)\n",
    "        data = resp.json()\n",
    "        # print(data)\n",
    "        if \"results\" in data:\n",
    "            r = data[\"results\"][0]\n",
    "            city = r[\"location\"][\"name\"]\n",
    "            # 当前天气对象\n",
    "            now = r[\"now\"]\n",
    "            text = now[\"text\"]\n",
    "            temp = now[\"temperature\"]\n",
    "            #python 擅长机器学习 和字符处理\n",
    "            return f\"{city}当前天气：{text}, 气温 {temp}度\"\n",
    "        else:\n",
    "            return \"查询失败\"\n",
    "    except Exception as e:\n",
    "        return  f\"异常：{e}\"\n",
    "    \n",
    "# print(get_weather(\"抚州\"))\n",
    "# {'results': [{'location': {'id': 'WSFXR95RZD21', 'name': '抚州', 'country': 'CN', 'path': '抚州,抚州,江西,中国', 'timezone': 'Asia/Shanghai', 'timezone_offset': '+08:00'}, 'now': {'text': '阴', 'code': '9', 'temperature': '8'}, 'last_update': '2025-11-18T20:37:05+08:00'}]}\n",
    "# 抚州当前天气：阴, 气温 8度\n",
    "from openai import OpenAI\n",
    "client=OpenAI(\n",
    "    api_key='sk-f0085aa7075f45ce946b9515da8c4cb2',\n",
    "    base_url='https://api.deepseek.com'\n",
    ")\n",
    "# openai 接口定义\n",
    "tools=[\n",
    "{\n",
    "    \"type\":\"function\",\n",
    "    \"function\":{\n",
    "        \"name\":\"get_weather\",\n",
    "        \"description\":\"获取制定城市的当前天气\",\n",
    "        \"parameters\":{\n",
    "            # 定义函数接受的参数结构\n",
    "            \"type\":\"object\",\n",
    "            # 定义了具体的参数属性\n",
    "            \"properties\":{\n",
    "                    \"location\":{\n",
    "                        \"type\":\"string\",\n",
    "                        # 北京天气怎么样？ 提取出来 北京\n",
    "                        \"description\":\"城市名称，如‘北京’\"\n",
    "                    }\n",
    "            },\n",
    "            \"required\":[\"location\"]\n",
    "        }\n",
    "    }\n",
    "}\n",
    "]\n",
    "\n",
    "import json\n",
    "messages=[{\"role\":\"user\",\"content\":\"北京天气怎么样\"}]\n",
    "response=client.chat.completions.create(\n",
    "    model='deepseek-reasoner',\n",
    "    messages=messages,\n",
    "    tools=tools,\n",
    "    tool_choice=\"auto\",\n",
    "    # 生成的随机度\n",
    "    temperature=0.1\n",
    ")\n",
    "response_message=response.choices[0].message\n",
    "print(response_message)\n",
    "messages.append(response_message)\n",
    "\n",
    "if response_message.tool_calls:\n",
    "    for tool_call in response_message.tool_calls:\n",
    "        print(tool_call.function)\n",
    "        function_name=tool_call.function.name\n",
    "        # json字符串 变成json对象\n",
    "        function_args=json.loads(tool_call.function.arguments)\n",
    "        if function_name==\"get_weather\":\n",
    "            function_response=get_weather(function_args[\"location\"])\n",
    "        else:\n",
    "            function_response=\"未知工具\"\n",
    "        \n",
    "        messages.append({\n",
    "            \"tool_call_id\":tool_call.id,\n",
    "            \"role\":\"tool\",\n",
    "            \"name\":function_name,\n",
    "            \"content\":function_response\n",
    "        })\n",
    "else:\n",
    "       print( response_message.content)\n",
    "\n",
    "final_response=client.chat.completions.create(\n",
    "    model=\"deepseek-reasoner\",\n",
    "    messages=messages,\n",
    "    temperature=0.3\n",
    ")\n",
    "# print(final_response.choices[0].message.content)"
   ],
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "ChatCompletionMessage(content='我来帮您查询北京的天气情况。', refusal=None, role='assistant', annotations=None, audio=None, function_call=None, tool_calls=[ChatCompletionMessageFunctionToolCall(id='call_00_7rmllIXLhYksPMfp9o6oLcJl', function=Function(arguments='{\"location\": \"北京\"}', name='get_weather'), type='function', index=0)])\n",
      "Function(arguments='{\"location\": \"北京\"}', name='get_weather')\n"
     ]
    }
   ],
   "execution_count": 6
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9b0ce1a6d79cd3b1",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": ".venv",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.14.0"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
